<template>
    <div class="base-page">
        <!-- 列表 -->
        <div class="right" v-if="viewList">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button type="primary"
                                @click="goAdd"
                            >新增</el-button>
                        </div>
                    </div>
                    <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="输入搜索关键字"
                            v-model="searchKey"
                            @select="onSearch"
                            @change="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                        <div class="adverse">
                            <el-button type="primary"
                                @click="onAdvanceSearch"
                            >高级搜索</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="e-table" :style="{width: rightTableWidth}">
                <el-table
                    class="table"
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                >
                    <el-table-column label="序号" type="index" width="55" fixed> </el-table-column>
                    <el-table-column prop="materialNumber" label="物资编号"
                        fixed
                        min-width="200"
                        class-name="blue-column"
                        show-overflow-tooltip
                    >
                        <template slot-scope="{ row }">
                            <span @click="onEdit(row)">{{ row.materialNumber || '无' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="materialName" label="物资名称" min-width="200"> </el-table-column>
                    <el-table-column prop="spec" label="规格" width="200"> </el-table-column>
                    <el-table-column prop="unit" label="单位" width="200"></el-table-column>
                    <el-table-column prop="changedUnitStr" label="转换单位" width="200"></el-table-column>
                    <el-table-column prop="changedQuantity" label="转换数量" width="200"></el-table-column>
                    <!-- <el-table-column prop="unit" label="单位" width="200">
                        <template slot-scope="{ row }">
                            {{ row.isEnable ? '是' : '否' }}
                        </template>
                    </el-table-column> -->
                </el-table>
            </div>
            <Pagination
                :total="paginationInfo.total"
                :pageSize.sync="paginationInfo.pageSize"
                :currentPage.sync="paginationInfo.currentPage"
                @currentChange="onCurrentChange"
                @sizeChange="onSizeChange"
            />
        </div>
        <!-- 新增编辑界面 -->
        <div class="right" v-else>
            <div class="e-form" style="padding: 0 10px 10px;">
                <div class="tabs-title">{{ !formData.billId ? '新增' : '修改' }}转换单位</div>
                <el-form ref="form" :model="formData" label-width="150px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="物资编号：">
                                <el-input
                                    v-if="!formData.billId"
                                v-model="formData.materialNumber" placeholder="请选择物资">
                                    <i slot="suffix" class="el-icon-document-copy" @click="onSelectMaterial"
                                    ></i>
                                </el-input>
                                <span v-else></span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="物资名称：">
                                {{ formData.billId ? '' : (formData.materialName || '请选择物资') }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="规格：">
                                {{ formData.billId ? '' : (formData.spec || '请选择物资') }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="单位：">
                                {{ formData.billId ? '' : (formData.unit || '请选择物资') }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="转换单位：">
                                <el-select v-model="formData.changedUnit" clearable placeholder="请选择转换单位"
                                >
                                    <el-option
                                        v-for="item in unitOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="转换数量：">
                                <el-input type="number" v-model="formData.changedQuantity"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="footer">
                <div class="right-btn">
                    <el-button type="primary"
                        @click="onSave"
                    >保存</el-button>
                    <el-button type="primary"
                        class="btn-delete"
                        v-if="formData.billId"
                        @click="onDel"
                    >删除</el-button>
                    <el-button
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import {
    getUnitConverLs,
    getUnitConverDetail,
    addUnitConver,
    modifyUnitConver,
    delUnitConver,
} from '@/api/base/material'
import { mapState, mapMutations, mapActions } from 'vuex'
import Pagination from '@/components/pagination/pagination'
import { debounce, showLoading, hideLoading, advanceSearch, selectDataClient, openAppClient } from '@/utils/common'
export default {
    components: {
        Pagination,
    },
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            tableData: [],
            paginationInfo: {
                total: 0,
                pageSize: 20,
                currentPage: 1,
            },
            attachTableData: [],
            formData: {
                billId: '',
                materialId: '',
                materialName: '',
                materialNumber: '',
                changedQuantity: '',
                changedUnit: '',
                spec: '',
                unit: ''
            },
            tabsName: 'baseInfo',
            tableData2: [],
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: []
        }
    },
    computed: {
        ...mapState('equip', ['equipData']),
        unitOptions () {
            return this.equipData.unitMeasure
        },
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 42) + 'px'
        },
        // 列表宽度
        rightTableHeight () {
            return this.paginationInfo.total ? (this.screenHeight - 172) : (this.screenHeight - 120)
        },
        // tabs内表格宽度
        rightTabsWidth () {
            return (this.screenWidth - 300) + 'px'
        },
        rightTabsHeight () {
            return (this.screenHeight - 83) + 'px'
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 103 - this.lastConHeight
        },
    },
    mounted () {
        this.getList()
        // 获取计量单位
        this.setUnitMeasur()
        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        ...mapActions('equip', ['setUnitMeasur']),
        async getList () {
            showLoading()
            try {
                const resData = await getUnitConverLs({
                    limit: this.paginationInfo.pageSize,
                    materialnumber: this.searchKey,
                    keyword: this.searchKey,
                    page: this.paginationInfo.currentPage
                })
                hideLoading()
                resData.list.forEach(item => {
                    let findObj = this.unitOptions.find(unit => unit.value === item.changedUnit)
                    item.changedUnitStr = findObj?.label || ''
                })
                this.tableData = resData.list
                this.paginationInfo.total = resData.totalCount
            } catch (err) {
                this.tableData = []
                console.log(err.message)
                hideLoading()
            }
        },
        onCurrentChange () {
            this.getList()
        },
        onSizeChange () {
            this.getList()
        },
        onSelectMaterial () {
            selectDataClient({
                SelectServiceToken: '/common/CategorySelect', //客户端路径
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({
                    'categoryType': 3, //类别类型1：物资类型，2：设备类型，3：所有类别
                    'materialCategoryId': '0', //物资类别父级id
                    'equipmentCategoryId': '00000', //设备类别父级id
                    'isUpdate': false, //true 基础库调用 false 其他地方调用(设备类别)
                    'estimatedMaterialLock': 0, //暂估物资锁(0：否;1：是;null:全部)(物资类别)
                    'materialType': 0//物资类型(0：一般材料;1:：周转材料;null:全部)(物资类别)
                }),
                Title: '选择物资' // 标题
            })
                .then(res => {
                    this.setSelectedInfo(res)
                    const data = res[0]
                    this.formData.materialName = data.className
                    this.formData.unit = data.unit
                    this.formData.materialId = data.billId
                })
            this.formData = {
                ...this.formData,
            }
            this.paginationInfo.currentPage = 1
            this.getList()
            // this.$Ajax.httpPost({
            //     url: '/material/categoryLibrary/queryListByParentClassId',
            //     params: {
            //         estimatedMaterialLock: 0, //暂估物资锁(0：否;1：是)
            //         isCentralizedPurchasing: 0,	//集中采购(0：否;1：是)
            //         parentiId: '', //父级id
            //         topClassNameNeed: [], //需要的物资类别(顶级类别名称)
            //         topClassNameNeedless: [], //不需要的物资类别(顶级类别名称)
            //     }
            // }).then(res => {
            //     return this.$Ajax.httpPost({
            //         url: '/material/baseLibrary/listByEntity',
            //         data: {
            //             classId: res[0].billId,
            //             limit: 10,
            //             page: 1,
            //             materialName: ''
            //         }
            //     })
            // }).then(res => {
            //  this.setSelectedInfo(res)
            //     const data = res.list[0]
            //     this.formData.materialName = data.materialName
            //     this.formData.spec = data.spec
            //     this.formData.unit = data.unit
            //     this.formData.materialId = data.billId
            // })
            // this.formData = {
            //     ...this.formData,
            //     // ...val
            // }
            // this.paginationInfo.currentPage = 1
            // this.getList()
        },
        onSearch (e) {
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            console.log(searchKey)
            this.paginationInfo.currentPage = 1
            this.getList()
        },
        goAdd () {
            for (let key in this.formData) {
                this.formData[key] = ''
            }
            this.viewList = false
        },
        async onEdit ({ billId }) {
            this.viewList = false
            showLoading()
            const resData = await getUnitConverDetail({
                id: billId
            })
            hideLoading()
            resData.isEnable = resData.isEnable === 1
            Object.assign(this.formData, resData)
        },
        async onSave () {
            this.formData.isEnable = this.formData.isEnable ? 1 : 0
            this.formData.sporadicPurchaseQuota = this.formData.sporadicPurchaseQuota === '' ? 0 : Number(this.formData.sporadicPurchaseQuota)
            this.formData.temporaryDemandQuota = this.formData.temporaryDemandQuota === '' ? 0 : Number(this.formData.temporaryDemandQuota)
            showLoading()
            if (!this.formData.billId) {
                await addUnitConver(this.formData)
            } else {
                await modifyUnitConver(this.formData)
            }
            hideLoading()
            this.viewList = true
            this.paginationInfo.currentPage = 1
            this.getList()
        },
        async onDel () {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', async () => {
                showLoading()
                await delUnitConver({
                    id: this.formData.billId
                }).catch(e => {
                    console.log(e.message)
                    hideLoading()
                })
                hideLoading()
                this.viewList = true
                this.getList()
            })
        },
        onCancel () {
            this.viewList = true
        },
        onSelect () {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/hr/org/getOrgByUserId', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ['1439990097591140358'], // 已选中id
                Title: '选择机构用户' // 标题
            }).then(val => {
                // 保存用户选择返回数据到store
                this.setSelectedInfo(val)
                // 客户端弹窗预览结果
                // 参数依次为: 打开页面地址、标题、回调函数
                openAppClient('/showSelectedData', '选择结果', function () {
                    // alert('关闭后回调')
                })
            })
        },
        onAdvanceSearch () {
            advanceSearch().then(res => {
                alert(JSON.stringify(res))
            })
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .right {
     margin-left: 0
}
</style>
